﻿using Microsoft.Extensions.Configuration;
using SqlSugar;
using System;
using System.Linq;


namespace Ekton_Manage_InfrastructureCore.SqlSugarHelper
{
    public class SqlSugarInstance
    {
        private readonly IConfiguration _configuration;
        public SqlSugarInstance(IConfiguration configuration)
        {
            _configuration = configuration;

        }
        public static SqlSugarClient client = null;
        private static readonly object lockSugar = new object();

        internal SqlSugarClient GetInstance()
        {
            SqlSugarClient db = default;
            if (client == null)
                lock (lockSugar)
                {
                    //创建数据库对象
                    db = new SqlSugarClient(new ConnectionConfig()
                    {
                        ConnectionString = _configuration["Db:SqlServer:ConnectionData:dbconn"],
                        DbType = DbType.SqlServer,
                        IsAutoCloseConnection = true
                    });

                    //添加Sql打印事件，开发中可以删掉这个代码
                    db.Aop.OnLogExecuting = (sql, pars) =>
                    {
                        Console.WriteLine(sql + "\r\n" + db.Utilities.SerializeObject(pars.ToDictionary(it => it.ParameterName, it => it.Value)));
                        Console.WriteLine();
                    };
                }
            return db;
        }
    }
}
